
/* 
 *	Space Trader Implementation - CS2340
 *	Designed by Andrew Mehlberg, Brandon Chastain, Jake Miller
 *
 *	Game launcher: Contains main game loop
 */
   
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

//#include "GuiTools.h"
//#include "GuiButton.h"
#include "StateManager.h"
#include "DBConnection.h"
#include <cppunit/CompilerOutputter.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/ui/text/TestRunner.h>

Uint32 initflags = SDL_INIT_VIDEO;  /* See documentation for details */
SDL_Surface *screen;
//Uint8  video_bpp = 0;
Uint32 videoflags = SDL_SWSURFACE;

void init() 
{
	
	/* Initialize the SDL library */
	if (SDL_Init(initflags) < 0) {
		fprintf(stderr, "Couldn't initialize SDL: %s\n",
				SDL_GetError());
		exit(1);
	}
	
	/* Set 640x480 video mode */
	screen = SDL_SetVideoMode(SCREEN_WIDTH,SCREEN_HEIGHT, SCREEN_BPP, SDL_SWSURFACE);
	if (screen == NULL) {
		fprintf(stderr, "Couldn't set 640x480x%d video mode: %s\n",
				SCREEN_BPP, SDL_GetError());
		SDL_Quit();
		exit(2);
	}
	//Initialize SDL_ttf
    if (TTF_Init() == -1) {
        fprintf(stderr, "ttf_init failed");   
    }
	//Set the window cpation
	SDL_WM_SetCaption("Space Trader", NULL);

}

int unitTest()
{
    CppUnit::Test *suite = CppUnit::TestFactoryRegistry::getRegistry().makeTest();
    CppUnit::TextUi::TestRunner runner;
    runner.addTest(suite);
    runner.setOutputter( new CppUnit::CompilerOutputter( &runner.result(), std::cerr ) );
    bool wasSucessful = runner.run();
    return wasSucessful ? 0 : 1;
}

int main(int argc, char *argv[])
{
	init();
	unitTest();
	StateManager game;
	//state_t = TITLE;
    state_t curr_state = game.render(screen);
	while(curr_state != QUIT){
        curr_state = game.render(screen);
        if (curr_state == SAVE){
            //save to file
            std::ofstream ofs("saveFile.sp");
            boost::archive::text_oarchive oa(ofs);
            oa << game;
			
			//save to DB
			std::stringstream ss;
			boost::archive::text_oarchive oaa(ss);
			oaa << game;
			DBSaveFileInsert(game.getPlayer()->getName(),ss.str());
			
            curr_state = QUIT;
        } else if (curr_state == LOADDB){
			std::stringstream ss(DBSaveFileRetrieve(game.getPlayer()->getName()));
			std::cout << "fail" << ss.str() << std::endl;
			if(ss.str()!="") {
				boost::archive::text_iarchive oa(ss);
				oa >> game;
				curr_state = PLANET;
				game.setState(PLANET);
			} else {
				curr_state = QUIT;
			}
        } else if (curr_state == LOAD) {
			//load statemanager
			std::ifstream ifs("saveFile.sp");
			boost::archive::text_iarchive ia(ifs);
			ia >> game;
			
			curr_state = PLANET;
            game.setState(PLANET);
		}
    }
	/* Clean up the SDL library */
	TTF_Quit();
	clean_up();
	SDL_Quit();
	return(0);
}
